import sys
import os.path
import os
import django
import csv
import chardet

pro_dir = os.getcwd()
sys.path.append(pro_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mitagger.settings")

from home.models import Image
from home.files import convertFormat

def get_image_path_dict():
    f = open('error_path_images', 'r')
    img_list = []
    img_dict = dict()
    for line in f:
        if f.endswith('\n'):
            line = line[:-1]
        img_list.append(line)
    basepath = 'uploads/'
    for parentDir, dirnames, filenames in os.walk(basepath):
        for filename in filenames:
            if filename in img_list:
                full_path = parentDir if parentDir.endswith('/') else parentDir+'/') + filename
                img_dict[filename] = full_path
    return img_dict

def get_missed_image_list(filename):
    namefile = open(filename, 'r')
    res = []
    for line in namefile:
        line = line[:-1] if line.endswith('\n') else line
        res.append(res)
    return res

def correct_fileformat(image_list):
    img_list = Image.objects.filter(file_name__in=image_list)
    for img in img_list:
        if img.image_file_location.endswith('.tif'):
            old_path = img.image_file_location
            img.image_file_location = convertFormat(old_path)
            try:
                img.save()
            except:
                print img.file_name
    print 'done'

def main():
    path_dict = get_image_path_dict()
    image_list = Image.objects.all()
    for img in image_list:
        if img.image_file_location == None or len(img.image_file_location) == 0:
            continue
        if not os.path.exists(img.image_file_location):
            if os.path.exists(img.image_file_location[:-4]+'.jpg'):
                img.image_file_location = img.image_file_location[:-4] + '.jpg'
                img.save()
                print 'ok'
            else:
                try:
                    img.image_file_location = path_dict[img.file_name]
                    img.save()
                except:
                    print img.file_name

if __name__ == '__main__':
    django.setup()
    correct_fileformat(get_missed_image_list('no_tags.txt', 'r'))
